package com.brainwave.utils;

import android.content.Context;
import android.util.Log;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import timber.log.Timber;

/**
 * 日志工具类
 * 提供统一的日志管理功能，支持文件日志和控制台日志
 */
public class Logger {
    
    private static final String TAG = "BrainWave";
    private static final String LOG_FILE_NAME = "brainwave.log";
    private static final long MAX_LOG_FILE_SIZE = 5 * 1024 * 1024; // 5MB
    
    private static Context context;
    private static File logFile;
    private static SimpleDateFormat dateFormat;
    private static boolean isInitialized = false;
    
    /**
     * 初始化日志系统
     */
    public static void init(Context ctx) {
        context = ctx.getApplicationContext();
        dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.getDefault());
        
        // 创建日志文件
        createLogFile();
        
        // 植入自定义的Timber树
        if (BuildConfig.DEBUG) {
            Timber.plant(new DebugTree());
        }
        Timber.plant(new FileLoggingTree());
        
        isInitialized = true;
        
        i(TAG, "Logger initialized successfully");
    }
    
    /**
     * 创建日志文件
     */
    private static void createLogFile() {
        try {
            File logDir = new File(context.getExternalFilesDir(null), "logs");
            if (!logDir.exists()) {
                logDir.mkdirs();
            }
            
            logFile = new File(logDir, LOG_FILE_NAME);
            
            // 检查文件大小，如果超过限制则重命名旧文件
            if (logFile.exists() && logFile.length() > MAX_LOG_FILE_SIZE) {
                File oldLogFile = new File(logDir, "brainwave_old.log");
                if (oldLogFile.exists()) {
                    oldLogFile.delete();
                }
                logFile.renameTo(oldLogFile);
                logFile = new File(logDir, LOG_FILE_NAME);
            }
            
        } catch (Exception e) {
            Log.e(TAG, "Failed to create log file", e);
        }
    }
    
    /**
     * 写入日志到文件
     */
    private static void writeToFile(String level, String tag, String message) {
        if (logFile == null) return;
        
        try (FileWriter writer = new FileWriter(logFile, true)) {
            String timestamp = dateFormat.format(new Date());
            String logEntry = String.format("%s [%s] %s: %s%n", timestamp, level, tag, message);
            writer.write(logEntry);
            writer.flush();
        } catch (IOException e) {
            Log.e(TAG, "Failed to write to log file", e);
        }
    }
    
    // ==================== 公共日志方法 ====================
    
    /**
     * Debug 日志
     */
    public static void d(String tag, String message) {
        if (isInitialized) {
            Timber.tag(tag).d(message);
        } else {
            Log.d(tag, message);
        }
    }
    
    public static void d(String tag, String message, Throwable throwable) {
        if (isInitialized) {
            Timber.tag(tag).d(throwable, message);
        } else {
            Log.d(tag, message, throwable);
        }
    }
    
    /**
     * Info 日志
     */
    public static void i(String tag, String message) {
        if (isInitialized) {
            Timber.tag(tag).i(message);
        } else {
            Log.i(tag, message);
        }
    }
    
    public static void i(String tag, String message, Throwable throwable) {
        if (isInitialized) {
            Timber.tag(tag).i(throwable, message);
        } else {
            Log.i(tag, message, throwable);
        }
    }
    
    /**
     * Warning 日志
     */
    public static void w(String tag, String message) {
        if (isInitialized) {
            Timber.tag(tag).w(message);
        } else {
            Log.w(tag, message);
        }
    }
    
    public static void w(String tag, String message, Throwable throwable) {
        if (isInitialized) {
            Timber.tag(tag).w(throwable, message);
        } else {
            Log.w(tag, message, throwable);
        }
    }
    
    /**
     * Error 日志
     */
    public static void e(String tag, String message) {
        if (isInitialized) {
            Timber.tag(tag).e(message);
        } else {
            Log.e(tag, message);
        }
    }
    
    public static void e(String tag, String message, Throwable throwable) {
        if (isInitialized) {
            Timber.tag(tag).e(throwable, message);
        } else {
            Log.e(tag, message, throwable);
        }
    }
    
    /**
     * Verbose 日志
     */
    public static void v(String tag, String message) {
        if (isInitialized) {
            Timber.tag(tag).v(message);
        } else {
            Log.v(tag, message);
        }
    }
    
    public static void v(String tag, String message, Throwable throwable) {
        if (isInitialized) {
            Timber.tag(tag).v(throwable, message);
        } else {
            Log.v(tag, message, throwable);
        }
    }
    
    // ==================== 特殊日志方法 ====================
    
    /**
     * 蓝牙相关日志
     */
    public static void bluetooth(String message) {
        i("Bluetooth", message);
    }
    
    public static void bluetooth(String message, Throwable throwable) {
        e("Bluetooth", message, throwable);
    }
    
    /**
     * 数据处理相关日志
     */
    public static void data(String message) {
        d("DataProcessor", message);
    }
    
    public static void data(String message, Throwable throwable) {
        e("DataProcessor", message, throwable);
    }
    
    /**
     * 网络相关日志
     */
    public static void network(String message) {
        d("Network", message);
    }
    
    public static void network(String message, Throwable throwable) {
        e("Network", message, throwable);
    }
    
    /**
     * UI相关日志
     */
    public static void ui(String message) {
        d("UI", message);
    }
    
    public static void ui(String message, Throwable throwable) {
        e("UI", message, throwable);
    }
    
    /**
     * 获取日志文件路径
     */
    public static String getLogFilePath() {
        return logFile != null ? logFile.getAbsolutePath() : null;
    }
    
    /**
     * 清除日志文件
     */
    public static void clearLogFile() {
        if (logFile != null && logFile.exists()) {
            logFile.delete();
            createLogFile();
            i(TAG, "Log file cleared");
        }
    }
    
    // ==================== 内部类 ====================
    
    /**
     * Debug模式下的Timber树
     */
    private static class DebugTree extends Timber.DebugTree {
        @Override
        protected void log(int priority, String tag, String message, Throwable t) {
            super.log(priority, tag, message, t);
        }
    }
    
    /**
     * 文件日志Timber树
     */
    private static class FileLoggingTree extends Timber.Tree {
        @Override
        protected void log(int priority, String tag, String message, Throwable t) {
            String level = getPriorityString(priority);
            String logMessage = message;
            
            if (t != null) {
                logMessage += "\n" + Log.getStackTraceString(t);
            }
            
            writeToFile(level, tag, logMessage);
        }
        
        private String getPriorityString(int priority) {
            switch (priority) {
                case Log.VERBOSE: return "V";
                case Log.DEBUG: return "D";
                case Log.INFO: return "I";
                case Log.WARN: return "W";
                case Log.ERROR: return "E";
                case Log.ASSERT: return "A";
                default: return "?";
            }
        }
    }
}